use std::fs;
use rusqlite::{Connection, Result};
use crate::data::{home_dir, db_path};

/// # 创建选择分类表
pub fn create_category_choose() -> Result<()> {
  let mut conn = Connection::open(db_path())?;
  let tr = conn.transaction()?;
  tr.execute("create table tb_category_choose(
      id text not null,
      category_id text not null
    ) ;", [])?;
  tr.execute("insert into tb_category_choose values('1','1');", [])?;
  tr.commit()?;
  Ok(())
}

/// # 创建仓库表
pub fn create_repo() -> Result<()> {
  let sql = "create table if not exists tb_repo (
    id TEXT not null  ,
    count INTEGER not null
  ) ; ";
  let conn = Connection::open(db_path())?;
  let _ = conn.execute(sql, [])?;
  Ok(())
}

/// # 创建订单表
pub fn create_order() -> Result<()> {
  let sql = "create table if not exists tb_order (
    id TEXT not null,
    goods_id TEXT not null,
    goods_name TEXT not null,
    sell_count INTEGER not null default 1,
    status INTEGER not null default 0,
    money INTEGER not null default 0,
    time TEXT not null ,
    phone TEXT not null,
    address TEXT not null
  ) ;";
  let conn = Connection::open(db_path())?;
  let _ = conn.execute(sql, []);
  Ok(())
}

/// #创建数据库表 tb_category
pub fn create_category() -> Result<Connection> {
  // window系统用户文件夹下创建data文件字符串
  let _db_path = home_dir().unwrap().join("data");
  // window系统用户文件夹下创建data文件夹
  let _ = fs::create_dir_all(&_db_path);
  // window系统用户文件夹data文件夹下, 创建 database.db 数据库文件
  let db_path = _db_path.join("database.db");
  // 输出测试
  // println!("home_path : {:?}", &db_path);
  // conn 连接数据库
  let conn = Connection::open(&db_path)?;
  // conn 创建表 tb_category
  conn.execute("create table if not exists tb_category (
    sort Text not null,
    id TEXT not null,
    name TEXT not null
  ) ;", [])?;

  Ok(conn)
}

/// # 创建商品表
pub fn create_goods() -> Result<()> {
  let sql = "create table if not exists tb_goods (
    id text not null ,
    category_id text not null ,
    type_name text ,
    color text ,
    name text not null  ,
    price integer not null ,
    count integer not null ,
    transport integer not null ,
    money integer null
);";
  let conn = Connection::open(db_path())?;
  conn.execute(sql, [])?;
  Ok(())
}








